package com.example.kemgdemo.service;

import com.example.kemgdemo.dto.req.LoginReq;
import com.example.kemgdemo.dto.req.RegisterReq;
import com.example.kemgdemo.enums.ExceptionEnum;
import com.example.kemgdemo.excepiton.BaseException;
import com.example.kemgdemo.model.UserEntity;
import com.example.kemgdemo.repository.UserRepository;
import org.dozer.DozerBeanMapper;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.UUID;

/**
 * 学号：1401030048
 * Created by 梁嘉伟 on 2019/7/12
 */
@Service
public class UserService {

    private final UserRepository userRepository;

    private final DozerBeanMapper dozerBeanMapper;

    public UserService(UserRepository userRepository, DozerBeanMapper dozerBeanMapper) {
        this.userRepository = userRepository;
        this.dozerBeanMapper = dozerBeanMapper;
    }

    public void userRegister(RegisterReq registerReq) {

        if (!Objects.nonNull(userRepository.getByUsername(registerReq.getUsername()))) {
            UserEntity userEntity = new UserEntity();
            dozerBeanMapper.map(registerReq, userEntity);
            try {
                userRepository.save(userEntity);
            } catch (Exception e) {
                throw new BaseException(ExceptionEnum.INSERT_FAILED);
            }
        } else {
            throw new BaseException(ExceptionEnum.USER_IS_EXIST);
        }
    }

    //todo token
    public String userLogin(LoginReq loginReq) {

        if (Objects.nonNull(userRepository.getByUsername(loginReq.getName()))) {
            //todo 添加权限
            return UUID.randomUUID().toString();
        } else {
            throw new BaseException(ExceptionEnum.USER_NOT_FOUND);
        }
    }
}
